/*
    Project: OCMF (Operant Chamber Management Framework)
    Version: 1.0
    Author: Copyright (C) 2010, Samuel Delaney & Andrew Harvey
    Licence:
        This file is part of OCMF.

            OCMF is free software: you can redistribute it and/or modify
            it under the terms of the GNU General Public License as published by
            the Free Software Foundation, either version 3 of the License, or
            (at your option) any later version.

            OCMF is distributed in the hope that it will be useful,
            but WITHOUT ANY WARRANTY; without even the implied warranty of
            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            GNU General Public License for more details.

            You should have received a copy of the GNU General Public License
            along with OCMF.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef PARALLELPORT_H
#define PARALLELPORT_H

#ifdef Q_WS_X11
#include <sys/io.h>
#endif

#include <QLibrary>
#include <QDebug>
#include "Logger.h"
#include <QThread>
#include <QMutex>
#include <QWaitCondition>


class ParallelPort : public QThread
{
public:
    ParallelPort();
    ParallelPort(short, short);

    void SetBit(short bit);
    void ClearBit(short bit);
    void TogglePort(short bit, unsigned int interval);
    void WaitForInput(short bit);

    unsigned int refreshRate;
private:
    void GetApiHooks();

    QLibrary inpout32Lib;

    short oldOutput, newOutput, oldInput, newInput;

    unsigned char inputBits[8];
    unsigned char outputBits[8];

    bool connected;
    short outputPortAddress, inputPortAddress;

//_stdcall required in order to call WIN32 API functions
#ifdef Q_WS_WIN
    typedef void _stdcall (*Out32Prototype)(short portAddress, short data);
    typedef short _stdcall (*Inp32Prototype)(short portAddress);
#endif

//_stdcall probably won't compile under linux and so is removed from function prototypes
#ifdef Q_WS_X11
    typedef void (*Out32Prototype)(short portAddress, short data);
    typedef short (*Inp32Prototype)(short portAddress);
#endif

    Out32Prototype Out32;
    Inp32Prototype Inp32;

    QMutex portMutex;
    QWaitCondition initWait;
protected:
    void run();
};

#endif // PARALLELPORT_H
